import random
import ConfigSpace as CS
import ConfigSpace.hyperparameters as CSH
import itertools
import onnx
from onnx import helper

class ConstantOfShape:
    cs_attributes = CS.ConfigurationSpace()
    attribute_list = ['value']
    all_attributes = []

    def __init__(self):
        print('ConstantOfShape Init--------------------------')
        self.init_all_attributes()
        self.init_cs()

    def init_all_attributes(self):
        for i in range(1, len(ConstantOfShape.attribute_list)+1) :
            #此处取所有组合的可能值，存在列表里
            for attribute in itertools.combinations(ConstantOfShape.attribute_list, i):
                l = list(attribute)
                ConstantOfShape.all_attributes.append(l)

        #print('all_attributes: ', all_attributes)
        print('all attributes:')
        for a in ConstantOfShape.all_attributes:
            print(a)

    def init_cs(self):
        length = len(ConstantOfShape.all_attributes)
        attributes = CSH.UniformIntegerHyperparameter(name='combination', lower=0, upper=length)
        ConstantOfShape.cs_attributes.add_hyperparameter(attributes)

    def get_random_combination(self):
        s = ConstantOfShape.cs_attributes.sample_configuration()
        index = s.get_dictionary()['combination']
        print('get combination: ', index)

        length = len(ConstantOfShape.all_attributes)
        if index >= length:
            index = length - 1

        return ConstantOfShape.all_attributes[index]       

    def get_max_attributes_combination(self):
        return len(ConstantOfShape.all_attributes)

    def get_attributes_by_index_or_random(self, shapes, index):

        print('get_attributes_by_index_or_random, index: ', index)    
            
        attributes = {}
        shape_out = []

        print('ConstantOfShape, shapes[0]:', shapes[0])

        if index != -1:
            attr_combination = ConstantOfShape.all_attributes[index]
        else:
            attr_combination = self.get_random_combination()

        if len(attr_combination) == 0:
            print('ConstantOfShape, shape_out:', shape_out)

            return attributes, shape_out    

        if 'value' in attr_combination:
            value = helper.make_tensor("value", onnx.TensorProto.FLOAT, [1], [random.randint(0, 1)])
            attributes['value'] = value

        print('------ attributes:', attributes, 'shape_out:', shape_out)

        return attributes, shape_out 

    def input_shape_correct(self, shapes):
        print('before:', shapes)

        shapes[0] = [random.randint(1, 5)]

        print('after:', shapes)

        return True
   